using System;
using LogSystem;
using System.Collections.Generic;
using com.youzu.warh.protocol;
using NodeCanvas.Framework;
using Pathfinding;
using Pathfinding.RVO;
using RootMotion.FinalIK;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using XLua;
using NpcFramework;
using UnityEditor;
using Yoozoo.Gameplay.Liberty.Pool;
using Yoozoo.Gameplay.Liberty.VehicleController;
using Yoozoo.Mars.Got;
using AnimationState = Yoozoo.Gameplay.Liberty.AI.AnimationState;
using Random = UnityEngine.Random;

namespace Yoozoo.Gameplay.Liberty.PlayerController
{

    public enum ControlMode
    {
        Input = 1,          // 输入模式
        AutoNav = 2,        // 自动寻路模式
        Hanging = 3,        // 挂机模式
        DriveCar = 4,       // 驾驶车辆模式
    }

    [Serializable]
    public class AutoNavParameters
    {
        public enum AutoNavType
        {
            None = 0,
            Normal = 1,
            RobCar = 2,
        }

        public AutoNavType navType = AutoNavType.None;

        public SpeedStrategyType speedStrategyType = SpeedStrategyType.Curve;
        
        public float maxSpeed = 1.0f;
        public float endReachedDistance = 0.1f;
        public float slowDistance = 4f;

        public float maxAnimSpeedScale = 1.02f;
        public float minAnimSpeedScale = 0.4f;
    }
    
    /// <summary>
    /// 玩家控制模式的管理、切换等
    /// </summary>
    public class PlayerControlModeMgr : MonoBehaviour
    {
        [SerializeField]
        private ControlMode controlMode = ControlMode.Input;
        public ControlMode ControlMode => controlMode;

        public List<AutoNavParameters> navParametersList;

        public PlayerViewAvatar viewAvatar;
        
        public PlayerCameraController cameraController;

        public PlayerVehicleController vehicleController;

        public PlayerVehicleBehaviourMgr vehicleBehaviourMgr;
        
        private PlayerStaminaBar _playerStaminaBar;

        public PlayerStaminaBar playerStaminaBar
        {
            get
            {
                return _playerStaminaBar;
            }
            set
            {
                _playerStaminaBar = value;
                if (_playerStaminaBar == null)
                {
                    return;
                }
                var boneController = playerModel.gameObject.GetComponent<BoneItemController>();
                if (boneController)
                {
                    _playerStaminaBar.SetFollowTransform(boneController.GetBoneItem("head"));
                }
                
            }
        }

        public bool CanAnimationStateSprint
        {
            get
            {
                switch (playerEntity.AIEntity.data.animationState)
                {
                    case AnimationState.Idle:
                    case AnimationState.Locomotion:
                    case AnimationState.HandGunShoot:
                    case AnimationState.HandGunReload:
                    case AnimationState.Sprinting:
                    case AnimationState.DodgeSprint:
                    {
                        return true;
                    }
                }
                return false;
            }
        }
        
        public Transform playerModel => viewAvatar.playerModel;
        public CharacterController characterCtrl;
        public Transform playerSeeker;
        public RVOController rvoController;
        public LocomotionAgent playerAgent => viewAvatar.locomotionAgent;
        
        public CapsuleCollider playerCollider => viewAvatar.controllerCollider;
        public CapsuleCollider playerOnHitTrigger => viewAvatar.onHitTrigger;
        public SphereCollider playerHeadTrigger => viewAvatar.headTrigger;
        public Rigidbody rigidBody => viewAvatar.rigidbody; 

        public PlayerInputController inputController;
        public InputRootMotion inputRootMotion => viewAvatar.inputRootMotion;
        public PlayerInputCamera inputCamera;
        public PlayerAnimInput animInput;
        public CameraInputData inputCameraInputData => inputCamera.cameraInputData;
        public PlayerEntity playerEntity;
        public CarEntity carEntity;

        public PlayerLockTargetHelper playerLockTargetHelper;

        public GraphOwner graphOwner;
        public Blackboard blackBoard;

        public PlayerVariables variables;
        public InteractionSystem InteractionSystem => viewAvatar.interactionSystem;

        [Space(25)]
        public Transform debugTarget;
        [Range(0.1f,5f)]
        public float debugSpeed = 2.0f;

        [HideInInspector]
        public string behaviorCameraName = "";
        
        [Space(25)]
        public Transform debugModel;
        
        // 临时存储周围的敌人
        private int[] _enemiesAround = null;
        // 临时存储周围的敌人是否是Boss
        private bool[] _enemiesAroundIsBoss = null;
        
        // 投掷手雷距离曲线
        [SerializeField]
        private AnimationCurve _GrenadeDistanceCurve = AnimationCurve.Linear(0,0,1,1);
        // 投掷手雷高度曲线
        [SerializeField]
        private AnimationCurve _GrenadeHeightCurve = AnimationCurve.Linear(0,0,1,1);
        // 投掷手雷默认最大距离
        [SerializeField]
        private float _GrenadeRange = 30;
        // 投掷手雷最小高度
        [SerializeField]
        private float _GrenadeMinHeight = 1;
        // 投掷手雷最大高度
        [SerializeField]
        private float _GrenadeMaxHeight = 6;

        #region 数据获取

        public Vector3 Velocity
        {
            get
            {
                if (controlMode == ControlMode.DriveCar && carEntity != null)
                {
                    return carEntity.carController.getRigidbody().velocity;
                }
                else if (controlMode == ControlMode.Input)
                {
                    if (rigidBody)
                    {
                        return rigidBody.velocity;
                    }
                }
                else
                {
                    if (characterCtrl)
                    {
                        return characterCtrl.velocity;
                    }
                }
                return Vector3.zero;
            }
        }

        public Vector3 Position
        {
            get
            {
                if (controlMode == ControlMode.DriveCar && carEntity != null)
                {
                    return carEntity.carController.getRigidbody().position;
                }
                else
                {
                    if (playerModel)
                    {
                        return playerModel.position;
                    }

                    if (playerSeeker)
                    {
                        return playerSeeker.position;
                    }
                }

                return Vector3.zero;
            }
        }

        public Quaternion Rotation
        {
            get
            {
                if (controlMode == ControlMode.DriveCar && carEntity != null)
                {
                    return carEntity.carController.getRigidbody().rotation;
                }
                else
                {
                    if (playerModel)
                    {
                        return playerModel.rotation;
                    }

                    if (playerSeeker)
                    {
                        return playerSeeker.rotation;
                    }
                }
                
                return Quaternion.identity;
            }
        }

        public Vector3 Forward
        {
            get
            {
                if (controlMode == ControlMode.DriveCar && carEntity != null)
                {
                    return carEntity.carController.getRigidbody().transform.forward;
                }
                else
                {
                    if (playerModel)
                    {
                        return playerModel.forward;
                    }

                    if (playerSeeker)
                    {
                        return playerSeeker.forward;
                    }
                }
                return Vector3.forward;
            }
        }

        public Vector3 DeltaPosition
        {
            get
            {
                
                
                return Vector3.zero;
            }
        }
        #endregion
        
        public void InitPlayerModel(GameObject model)
        {
            InitData();
            
            viewAvatar.InitAvatar(model,playerEntity.AIEntity);
            playerEntity.AIEntity.viewer.animator = viewAvatar.animator;
            //playerEntity.AIEntity.viewer.transform = viewAvatar.playerModel;
            playerEntity.AIEntity.viewer.boneItemController = viewAvatar.boneItemController;
            playerEntity.AIEntity.characterController = characterCtrl;
            AnimationAgent animationAgent = viewAvatar.playerModel.GetOrAddCompoment<AnimationAgent>();
            animationAgent.InitData(playerEntity.AIEntity);
            playerEntity.AIEntity.viewer.animationAgent = animationAgent;
            
            BattleAgent battleAgent = viewAvatar.playerModel.GetOrAddCompoment<BattleAgent>();
            battleAgent.InitData(playerEntity.AIEntity);
            playerEntity.AIEntity.battleAgent = battleAgent;
            playerLockTargetHelper = viewAvatar.playerModel.GetOrAddCompoment<PlayerLockTargetHelper>();
            playerLockTargetHelper.InitData(playerEntity.AIEntity);

            inputController.rigidBody = viewAvatar.rigidbody;
            inputController.animInput.animator = viewAvatar.animator;
            inputController.aiEntity = playerEntity.AIEntity;

            Set2InputCamera();
            
            cameraController.viewerRoot = viewAvatar.playerModel;
            viewAvatar.locomotionAgent.seeker = playerSeeker.GetComponent<LibertyNpcSeeker>();
            viewAvatar.locomotionAgent.immediateRotate = false;

            viewAvatar.locomotionAgent.seeker.aiPath.updatePosition = true;
            viewAvatar.locomotionAgent.seeker.aiPath.updateRotation = true;
            
            inputCamera.Init();
            
            InitMode();
            
        }

        public void Set2InputCamera()
        {
            cameraController.inputCameraConfig.followTarget.rigidbody = viewAvatar.rigidbody;
            viewAvatar.inputRootMotion.OnSet2InputCamera();
            cameraController.inputCameraConfig.followTarget.InputRootMotion = viewAvatar.inputRootMotion;
            inputCamera.SetCameraFollowTarget(cameraController.inputCameraConfig.followTarget);
            inputCamera.SetCameraInitializedData(cameraController.inputCameraConfig.initializedData);
            inputCamera.SetCameraInputData(cameraController.inputCameraConfig.cameraInputData);
        }

        private void InitData()
        {
            playerEntity.AIEntity.data.distanceToPlayer = 0;
            playerEntity.AIEntity.data.directionToPlayer = Vector3.zero;
            playerEntity.AIEntity.setPropertyDataConfig(LibertyConfigManager.GetInstance().GetAIPropertyDataConfig(LibertyConfigManager.PLAYER_PROPERTY_NPCID));
        }
        
        private void InitMode()
        {
            //blackBoard.SetVariableValue("AIEntity", playerEntity.AIEntity);
            //variables.playerController = this;
            
            // 同步角色控制器参数给玩家输入模式下的碰撞器
            playerCollider.center = new Vector3(characterCtrl.center.x,characterCtrl.center.y,characterCtrl.center.z);
            playerCollider.radius = characterCtrl.radius;
            playerCollider.height = characterCtrl.height;
            
            // 伤害触发器
            playerOnHitTrigger.center = playerCollider.center + new Vector3(0, -0.2f, 0);
            playerOnHitTrigger.radius = playerCollider.radius + 0.2f;
            playerOnHitTrigger.height = playerCollider.height-0.3f;
            playerEntity.AIEntity.onHitCollider = playerOnHitTrigger;
            
            // 头部伤害触发器
            playerHeadTrigger.center = new Vector3(0,playerCollider.height-0.2f, 0);
            playerHeadTrigger.radius = 0.2f;
            playerEntity.AIEntity.headCollider = playerHeadTrigger;
            
            inputCamera.Active = true;
            rvoController.enabled = false;
            if (controlMode == ControlMode.Input)
            {
                controlMode = ControlMode.AutoNav;
                Switch2InputMode();
            }
            else if (controlMode == ControlMode.AutoNav)
            {
                controlMode = ControlMode.Input;
                Switch2AutoNavMode();
            }
            else if (controlMode == ControlMode.Hanging)
            {
                controlMode = ControlMode.Input;
                Switch2HangingMode();
            }

            inputCamera.ControlMode = CameraControlMode.Follow;
            SwitchNavParameter(AutoNavParameters.AutoNavType.Normal);
            
            BlueprintUtils.PlayerController = this;
            LibertyAIUtils.PlayerController = this;

            if (LibertyAIUtils.AIManager)
            {
                LibertyAIUtils.AIManager.AddAIEntity(playerEntity.AIEntity);
            }
            
            playerAgent.RegistSeeker(playerEntity.AIEntity.seeker,
                playerEntity.AIEntity,
                playerEntity.AIEntity.characterController);

        }

        private void OnDisable()
        {
            if (ControlMode != ControlMode.DriveCar)
            {
                Switch2InputMode();
            }
        }

        private void OnDestroy()
        {
            BlueprintUtils.PlayerController = null;
            LibertyAIUtils.PlayerController = null;
            
            if (_enemiesAround != null)
            {
                _enemiesAround = null;
            }
            if (_enemiesAroundIsBoss != null)
            {
                _enemiesAroundIsBoss = null;
            }
        }

        private float _cameraFollowTime = 0;

        private float _navModeDuration = 0;
        
        private void FixedUpdate()
        {
            //判断角色腰部位置和摄像机的距离使角色产生半透明效果
            Shader.SetGlobalVector("roleWldPos",Position + new Vector3(0, 1.1f, 0));
            
            if (controlMode != ControlMode.Input)
            {
                _navModeDuration += Time.fixedDeltaTime;
            }
            else
            {
                _navModeDuration = 0;
            }

            if (_navModeDuration > 0.5f) 
            {
                if (Mathf.Abs(inputController.playInput.HorValue) > 0.1f ||
                    Mathf.Abs(inputController.playInput.VerValue) > 0.1f || 
                    inputController.playInput.IsSprint ||
                    inputController.playInput.IsDodge) 
                {
                    if (controlMode == ControlMode.AutoNav || controlMode == ControlMode.Hanging)
                    {
                        Switch2InputMode();
                        // 打断导航到车辆的逻辑
                        vehicleBehaviourMgr.BreakNav2Door();
                    }
                }
            }

            // 是否使用第一人称视角
            inputCamera.UseFirstPerson = playerEntity.AIEntity.data.aimingState != AimingState.None;//playerLockTargetHelper.UseFreeAim;
            
            if (Mathf.Abs(inputController.playInput.CameraHorValue) > 0.1f || 
                Mathf.Abs(inputController.playInput.CameraVerValue) > 0.1f)
            {
                if (inputCamera.ControlMode == CameraControlMode.Follow || 
                    inputCamera.ControlMode == CameraControlMode.StreetBattle)
                {
                    inputCamera.ControlMode = CameraControlMode.Input;
                    _cameraFollowTime = 0;
                }
            }
            else
            {
                if (inputCamera.ControlMode == CameraControlMode.Input)
                {
                    _cameraFollowTime += Time.fixedDeltaTime;
                    
                    AIEntity aiEntity = playerEntity.AIEntity;
                    AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
                    bool isReloading = false;//Time.time < animationAgent.reloadFinishTimestamp;
                    
                    if (_cameraFollowTime > 1f && (playerEntity.AIEntity.data.aimingState==AimingState.None || isReloading)) // 规定时间不操作，切换到跟随模式
                    {
                        inputCamera.ControlMode = CameraControlMode.Follow;
                    }
                }
            }
            
        }

        
        
        // 设置寻路层
        public void SetPlayerNavMask(string[] masks)
        {
            // 设置寻路层
            var seeker = playerSeeker.GetComponent<Seeker>();
            int maskValue = 0;
            foreach (var m in masks)
            {
                maskValue |= GraphMask.FromGraphName(m);
            }
            seeker.graphMask = maskValue;
        }

        public void SwitchNavParameter(AutoNavParameters.AutoNavType autoNavType)
        {
            foreach (var np in navParametersList)
            {
                if (np.navType == autoNavType)
                {
                    playerEntity.AIEntity.data.speedStrategy = np.speedStrategyType;
                    
                    var seeker = playerEntity.AIEntity.seeker;
                    //seeker.SwitchSpeedStrategy(np.speedStrategyType);
                    seeker.SetMaxSpeed(playerEntity.AIEntity.propertyDataConfig.move_speed * np.maxSpeed);
                    seeker.aiPath.maxSpeed = np.maxSpeed;
                    playerEntity.AIEntity.data.maxSpeed = np.maxSpeed;
                    seeker.SlowDistance = np.slowDistance;
                    seeker.aiPath.endReachedDistance = np.endReachedDistance;

                    // viewAvatar.locomotionAgent.maxAnimSpeedScale = np.maxAnimSpeedScale;
                    // viewAvatar.locomotionAgent.minAnimSpeedScale = np.minAnimSpeedScale;
                }
            }
        }
        
        public void Switch2HangingMode()
        {
            if (controlMode == ControlMode.Hanging) return;
            controlMode = ControlMode.Hanging;
            AutoModeSetting();
            //cameraController.Switch2HangingCamera();
            cameraController.Switch2BehaviorCamera("hanging");
        }
        
        public void Switch2AutoNavMode()
        {
            if (controlMode == ControlMode.AutoNav) return;
            controlMode = ControlMode.AutoNav;
            AutoModeSetting();
            cameraController.Switch2InputCamera();
        }

        // 只会从导航模式切换过来
        public void Switch2DriveCarMode(CarEntity carEntity)
        {
            if (controlMode == ControlMode.DriveCar) return;
            controlMode = ControlMode.DriveCar;
            this.carEntity = carEntity;
            viewAvatar.locomotionAgent.SetCarEntity(carEntity.carBase);
        }

        public void ClearCarEntity()
        {
            carEntity = null;
        }
        
        private void AutoModeSetting()
        {
            //rvoController.enabled = true;
            rigidBody.isKinematic = true;
            rigidBody.useGravity = false;
            playerCollider.enabled = false;
            playerSeeker.gameObject.SetActive(true);
            playerAgent.enabled = true;

            inputController.Active = false;
            inputRootMotion.Active = false;
            inputCamera.ControlMode = CameraControlMode.Follow; 
            animInput.Active = false;

            // 同步位置
            var viewer = playerEntity.AIEntity.viewer;
            var pData = playerEntity.AIEntity.data;
            
            pData.position = playerModel.position;
            pData.CurrentLerpRotation = playerModel.rotation.eulerAngles;
            
            playerEntity.AIEntity.SetPositionAndRotation(pData.position,playerModel.rotation.eulerAngles);
            playerAgent.RegistSeeker(playerEntity.AIEntity.seeker,playerEntity.AIEntity,characterCtrl);
            
            playerEntity.AIEntity.seeker.RegisterAgent(viewer.transform,playerAgent);
            playerEntity.AIEntity.seeker.SetForceUpdateTargetRotation(pData.rotation);
            playerEntity.AIEntity.seeker.SetPosition(pData.position);
            playerEntity.AIEntity.seeker.transform.forward = pData.forward;
            playerEntity.AIEntity.seeker.SetDestination(pData.position);

            if (cameraController.behaviorCameraCollection)
            {
                cameraController.behaviorCameraCollection.transform.position = pData.position;
                cameraController.behaviorCameraCollection.transform.rotation = pData.rotation;
                // foreach (var behaviorCamera in behaviorCameraRoot.cameras)
                // {
                //     if (behaviorCamera!=null)
                //     {
                //         behaviorCamera.virtualCamera.transform.position =
                //             pData.position + behaviorCamera.virtualCamera.transform.localPosition;
                //         behaviorCamera.virtualCamera.transform.rotation =
                //             pData.rotation * behaviorCamera.virtualCamera.transform.localRotation;
                //     }
                // }
            }
            
            blackBoard.SetVariableValue("ControlMode", controlMode);
        }
        
        public void Switch2InputMode()
        {
            if (controlMode == ControlMode.Input) return;
            //rvoController.enabled = true;
            controlMode = ControlMode.Input;
            if (rigidBody)
            {
                // rigidBody.isKinematic = false;
                // rigidBody.useGravity = true;
            }
            playerCollider.enabled = true;
            playerSeeker.gameObject.SetActive(false);
            playerAgent.enabled = false;

            inputController.Active = true;
            inputRootMotion.Active = true;
            animInput.Active = true;

            Vector3 pos = playerModel.position;
            Vector3 rot = playerModel.eulerAngles;
            
            playerEntity.AIEntity.data.moveSpeed = 0;

            inputRootMotion.SetPosition(pos,rot);
            
            inputController.LastDirection = playerModel.transform.forward;
            
            cameraController.Switch2InputCamera();
            
            blackBoard.SetVariableValue("ControlMode", controlMode);
        }

        public void OnRegainBalance()
        {
            inputController.LastDirection = playerModel.transform.forward;
            inputController.Active = true;
        }

        public void SwitchRootMotion(bool allow)
        {
            inputRootMotion.Active = allow;
        }
        public void SwitchMovementInput(bool allow)
        {
            inputController.playInput.CloseMoveInput = !allow;
            if (!allow)
            {
                //关闭移动时复原一些参数
                rigidBody.velocity = Vector3.zero;
                inputController.animInput.SetSpeed(0);
                LibertyAIUtils.PlayerController.SetPlayerNavSpeed(0);
            }
        }

        public void SwitchCameraInput(bool allow)
        {
            inputController.playInput.CloseCameraInput = !allow;
        }

        public void OnlySwitchCameraInput(bool allow)
        {
            inputCamera.Active = allow;
        }
        public void SwitchPlayerInputController(bool allow)
        {
            inputController.Active = allow;
        }

        public void SwitchPlayerRigidBodyKinematic(bool isKinematic)
        {
            rigidBody.isKinematic = isKinematic;
        }

        // 局部坐标
        public void SetInputCameraAngle(float h, float v)
        {
            //inputCamera.SetAngle(h,v);
        }

        public void SetInputCameraInitAngle()
        {
            inputCamera.ResetCamera();
        }

        public void TaskAutoNavToTarget(Vector3 target)
        {
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            if (animationAgent)
            {
                // animationAgent.EnterBattleState(BattleState.None);
                animationAgent.EnterAimingState(AimingState.None);
            }
            
            SetPlayerDestination(target, NavType.Task);
        }

        public void NavPlayerTransmission(Vector3 pos, Vector3 rot)
        {
            var pData = playerEntity.AIEntity.data;
            playerModel.transform.localPosition = Vector3.zero;
            playerModel.transform.localEulerAngles = Vector3.zero;
            pData.CurrentLerpRotation = rot;
            pData.position = pos;
            playerEntity.AIEntity.SetPositionAndRotation(pos,rot);
            playerEntity.AIEntity.seeker.SetForceUpdateTargetRotationAndPosition(pData.rotation,pData.position);
        }
        
        public void PlayerTransmission(Vector3 pos, 
            Vector3 rot,
            bool resetCamera = true,
            bool forceActive = true)
        {

            if (forceActive && !transform.gameObject.activeSelf)
            {
                transform.gameObject.SetActive(true);
            }

            if (controlMode == ControlMode.DriveCar)
            {
                if (carEntity)
                {
                    carEntity.carController.immobilize();
                    carEntity.carController.setPosition(pos);
                    carEntity.carController.setRotation(Quaternion.Euler(rot));
                    if (resetCamera)
                    {
                        LibertyAIUtils.PlayerController.inputCamera.ResetCamera();
                    }
                }
                return;
            }
            
            inputRootMotion.checkGround = false;
            if (rigidBody)
            {
                rigidBody.useGravity = false;
            }
            Timers.inst.Add(3,1,(o =>
            {
                inputRootMotion.checkGround = true;
            }));

            if (controlMode == ControlMode.AutoNav || 
                controlMode == ControlMode.Hanging)
            {
               NavPlayerTransmission(pos,rot);
            }
            else if (controlMode == ControlMode.Input)
            {
                viewAvatar.locomotionAgent.enabled = false;
                // 获取当前输入相机的相对角度
                //float localAngleH = inputCamera.LocalAngleH;
                //float localAngleV = inputCamera.LocalAngleV;
                
                var viewer = playerEntity.AIEntity.viewer;
                viewer.transform.position = Vector3.zero;
                viewer.transform.eulerAngles = Vector3.zero;

                inputRootMotion.SetPosition(pos,rot);
                playerEntity.AIEntity.data.CurrentLerpRotation = rot;
                // playerModel.eulerAngles = rot;

                inputController.LastDirection = playerModel.transform.forward;
                // if (setInputModelCameraRotate)
                // {
                //     inputCamera.SetAngle(localAngleH,localAngleV);
                // }
            }

            if (resetCamera)
            {
                inputCamera.ResetCamera();
            }
            
        }

        public void SetPlayerDestination(Vector3 destination, NavType navType = NavType.None)
        {
            if (!CanAnimationStateSprint || inputRootMotion.isOutPlayerControl)
            {
                return;
            }
            
            if (vehicleBehaviourMgr.enterExitCarState != EnterExitCarState.None)
            {
                if (navType != NavType.Nav2Car)
                {
                    // 上下车和车辆行驶时，禁用寻路
                    return;
                }
            }

            if (controlMode == ControlMode.AutoNav &&
                variables.gotoDestination &&
                Vector3.Distance(playerEntity.AIEntity.data.destination,destination) < 0.1f)
            {
                // 重复调用寻路
                return;
            }

            playerEntity.AIEntity.seeker.transform.position = playerModel.transform.position;
            playerEntity.AIEntity.seeker.transform.rotation = playerModel.transform.rotation;
            
            if (controlMode == ControlMode.Input)
            {
                Switch2AutoNavMode();
            }

            //rvoController.enabled = true;
            viewAvatar.locomotionAgent.immediateRotate = true;
            playerEntity.AIEntity.data.destination = destination;
            playerEntity.AIEntity.seeker.SetDestination(destination);
            variables.gotoDestination = true;
            variables.navType = navType;
        }
        
        public void SetDestinatonWithCallBack(Vector3 destination, NavType navType, LuaFunction callBack)
        {
            var customPath = playerSeeker.GetComponent<CustomPath>();
            customPath.onReached = () => { callBack.Action(0); };
        }

        public void SetPlayerNavSpeed(float maxSpeed)
        {
            // if (maxSpeed <= 0.1)
            // {
            //     maxSpeed = 1f;
            // }
            
            playerEntity.AIEntity.data.maxSpeed = maxSpeed;
            playerEntity.AIEntity.seeker.SetMaxSpeed(playerEntity.AIEntity.propertyDataConfig.move_speed * maxSpeed);
            playerEntity.AIEntity.seeker.SetPriority(1f);
        }
        
        public void Face2Position(Vector3 position,bool resetCamera = true)
        {
            Vector3 playerPos = GetPlayerPosition();
            playerPos.y = 0;
            position.y = 0;
            Vector3 forward = (position - playerPos).normalized;
            Vector3 eulerAngles =  Quaternion.LookRotation(forward).eulerAngles;
            PlayerTransmission(GetPlayerPosition(),eulerAngles,resetCamera);
        }
        
        public Vector3 GetPlayerPosition()
        {
            return playerModel.position;
        }

        /// <summary>
        /// 获取当前战斗状态
        /// </summary>
        /// <returns></returns>
        public BattleState GetBattleState()
        {
            AIData aiData = playerEntity.AIEntity.data;
            return aiData.battleState;
        }

        /// <summary>
        /// 获取选择的武器
        /// </summary>
        /// <returns></returns>
        public int GetSelectedWeaponId(out int selectedGrenadeId)
        {
            selectedGrenadeId = 0;

            if (playerEntity.AIEntity.WeaponSystem.EquippedGrenade != null)
            {
                selectedGrenadeId = playerEntity.AIEntity.WeaponSystem.EquippedGrenade.Id;
            }

            return playerEntity.AIEntity.WeaponSystem.EquippedWeapon.Id;
        }

        public int GetHandleWeaponId()
        {
            return playerEntity.AIEntity.WeaponSystem.SelectedWeaponId;
        }
        public bool GetIsSelectGrenade()
        {
            return playerEntity.AIEntity.WeaponSystem.IsSelectedGrenade();
        }
        
        /// <summary>
        /// 选择已装备的武器
        /// </summary>
        /// <param name="isGrenade"> 手雷还是武器 </param>
        public void SwitchEquipmentWeapon(bool isGrenade)
        {
            var weaponId = 0;
            if (isGrenade)
            {
                if (playerEntity.AIEntity.WeaponSystem.EquippedGrenade != null)
                {
                    EuipAndSwitchWeapon(playerEntity.AIEntity.WeaponSystem.EquippedGrenade.Id);
                }
            }
            else
            {
                if (playerEntity.AIEntity.WeaponSystem.EquippedWeapon != null)
                {
                    EuipAndSwitchWeapon(playerEntity.AIEntity.WeaponSystem.EquippedWeapon.Id);
                }
            }
        }

        public void EuipAndSwitchWeapon(int weaponId)
        {
            var weaponSys = playerEntity.AIEntity.WeaponSystem;
            weaponSys.EquipWeapon(weaponId);
            // AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            // BattleState battleState = BattleState.None;
            // PbWeaponDataConfig weaponDataConfig = LibertyConfigManager.GetInstance().GetWeaponDataConfig(weaponId);
            // if (weaponDataConfig != null)
            // {
            //     battleState = (BattleState)weaponDataConfig.battle_state;
            // }
            battleAgent.ChangeWeapon(weaponId);
            // // 是否可以直接切换
            // if (animationAgent.CanDoNextAnimation())
            // {
            //     animationAgent.EnterBattleState(battleState);
            //     animationAgent.EnterAimingState(AimingState.None);
            // }
        }
        /// <summary>
        /// 获取当前动画状态
        /// </summary>
        /// <returns></returns>
        public AnimationState GetAnimationState()
        {
            AIData aiData = playerEntity.AIEntity.data;
            return aiData.animationState;
        }
        
        /// <summary>
        /// 是否可以进行下个动作 (战斗动作必须等上个动作做完，才可以接下一步)
        /// </summary>
        /// <returns></returns>
        public bool CanDoNextAnimation()
        {
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            return animationAgent.CanDoNextAnimation();
        }
        
        /// <summary>
        /// 点击近战按钮
        /// </summary>
        public void TriggerBoxingAnimation()
        {
            AIData aiData = playerEntity.AIEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            // 切换状态
            if (EnterAimingState(AimingState.NormalAim))
            {
                return;
            }
            
            // Debug.LogError(LogModule.LibertySceneBattle, $"{animationAgent.boxingTimestamp} < {Time.time} < {animationAgent.boxingBufferTimestamp}");
            // 切换相机模式
            inputCamera.ControlMode = CameraControlMode.Input;
 
            // 是否可以再次出招
            if (animationAgent.CanDoNextAnimation())
            {
                // 转向目标
                // battleAgent.FaceToCurrentLockTarget();

                // Debug.LogError(LogModule.LibertySceneBattle, $"TriggerBoxingAnimation: {aiData.moveSpeed}");
                AnimationAgent.BoxingMoveType boxingMoveType = AnimationAgent.BoxingMoveType.None;//battleAgent.CheckBoxingMoveTypeToCurrentLockTarget();

                if (Vector3.Dot(aiData.moveDirection, animationAgent.transform.forward)>0 && aiData.moveSpeed > 3.5f)
                {
                    animationAgent.PlayBoxingCombo2(boxingMoveType);
                }
                else
                {
                    animationAgent.PlayBoxingCombo1(boxingMoveType);
                }
                return;
                
                // if (battleAgent.CanAttackDownCurrentLockTarget())
                // {
                //     // 攻击倒地目标
                //     animationAgent.PlayBoxingAttackDown(boxingMoveType);
                // }
                // else if (aiData.animationState == AnimationState.Sprinting)
                // {
                //     // 跑动攻击
                //     animationAgent.PlayBoxingRunAttack();
                // }
                // else
                {
                    // 是否在缓冲时间内再次出招，用于连招
                    if (Time.time < animationAgent.nextComboBufferTimestamp)
                    {
                        switch (animationAgent.currentAnimationState)
                        {
                            case AnimationState.BoxingCombo1:
                                {
                                    animationAgent.PlayBoxingCombo2(boxingMoveType);    
                                }
                                break;
                            case AnimationState.BoxingCombo2:
                                {
                                    // if (Random.Range(0, 100) < 67)
                                    // {
                                    //     animationAgent.PlayBoxingAttackKick(boxingMoveType);                                    
                                    // }
                                    // else
                                    {
                                        animationAgent.PlayBoxingCombo3(boxingMoveType);   
                                    }
                                }
                                break;

                            case AnimationState.BoxingCombo3:
                            case AnimationState.BoxingAttackKick:
                            case AnimationState.BoxingAttackDown:
                            case AnimationState.Idle:
                            case AnimationState.Undefine:
                                {
                                    animationAgent.PlayBoxingCombo1(boxingMoveType);
                                }
                                break;
                        }
                    }
                    else
                    {
                        animationAgent.PlayBoxingCombo1(boxingMoveType);
                    }
                }
                
            }
            
        }

        public void TriggerBoxingAOEAnimation()
        {
            AIData aiData = playerEntity.AIEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            // 切换状态
            if (EnterAimingState(AimingState.NormalAim))
            {
                return;
            }
            
            // 是否可以再次出招
            if (animationAgent.CanDoNextAnimation() && Time.time>=animationAgent.boxingAOEColdFinishTimestamp)
            {
                // // 转向目标
                // battleAgent.FaceToCurrentLockTarget();

                animationAgent.PlayBoxingAOE();
            }
            
        }
        
        /// <summary>
        /// 获取近战AOE的cd
        /// </summary>
        /// <param name="cd">cd</param>
        /// <returns></returns>
        public float GetBoxingAOECD(out float cd)
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
            cd = animationAgent.boxingAOEColdDuration;
            return animationAgent.boxingAOEColdFinishTimestamp;
        }

        /// <summary>
        /// 切换到指定瞄准状态
        /// </summary>
        /// <param name="aimingState"></param>
        /// <returns>状态是否切换成功</returns>
        public bool EnterAimingState(AimingState aimingState,bool forceChanged = false)
        {
            AIData aiData = playerEntity.AIEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;

            if (!forceChanged && !animationAgent.CanDoNextAnimation())
            {
                return aiData.aimingState == aimingState;
            }

            if (aiData.aimingState != aimingState)
            {
                animationAgent.EnterAimingState(aimingState);
                return true;
            }

            return false;
        }
        
        /// <summary>
        /// 当前是否在瞄准状态
        /// </summary>
        /// <returns></returns>
        public bool IsInAimingState()
        {
            AIData aiData = playerEntity.AIEntity.data;
            return aiData.aimingState != AimingState.None;
        }
        
        public void OnEnterSprintMode()
        {
            // if (controlMode == ControlMode.AutoNav || controlMode == ControlMode.Hanging)
            // {
            //     Switch2InputMode();
            //     // 打断导航到车辆的逻辑
            //     vehicleBehaviourMgr.BreakNav2Door();
            // }
            
            AIData aiData = playerEntity.AIEntity.data;
            aiData.isSprint = true;
        }
        
        public void OnExitSprintMode()
        {
            AIData aiData = playerEntity.AIEntity.data;
            aiData.isSprint = false;
        }
        
        public void ExitAimState()
        {
            AIData aiData = playerEntity.AIEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            // if (aiData.battleState != BattleState.None)
            // {
            //     animationAgent.EnterBattleState(BattleState.None);
            // }
            if (aiData.aimingState != AimingState.None)
            {
                animationAgent.EnterAimingState(AimingState.None);
            }
        }
        
        /// <summary>
        /// 点击射击按钮
        /// </summary>
        public void TriggerGunFireAnimation(bool forceFire = false)
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            
            // 弹匣剩余子弹数量
            if (battleAgent.GetRestBulletCount() <= 0 && battleAgent.GetCapacityCount() > 0)
            {
                if (battleAgent.IsRestBulletCountEnough())
                {
                    // 武器还有子弹
                    if (!battleAgent.IsRestBulletCountFull())
                    {
                        TriggerGunReloadAnimation();
                    }
                }
                else
                {
                    // 没有子弹，切换武器
                    int weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(false);
                    if (weaponId > 0)
                    {
                        EuipAndSwitchWeapon(weaponId);
                    }
                }
                return;
            }
            
            // 切换瞄准状态
            EnterAimingState(AimingState.NormalAim);
            
            // 切换相机模式
            inputCamera.ControlMode = CameraControlMode.Input;

            if (forceFire || animationAgent.CanDoNextAnimation())
            {
                // // 距离是否过近
                // if (battleAgent.CanHandGunBoxingCurrentLockTarget())
                // {
                //     // 手枪近战攻击
                //     battleAgent.FaceToCurrentLockTarget();
                //     animationAgent.PlayHandGunBoxing();
                // }
                // else
                {
                    animationAgent.PlayGunFire();
                }
            }
        }

        public void TriggerNormalAnimaion()
        {
            EnterAimingState(AimingState.None, true);
        }
        
        /// <summary>
        /// 点击重新装弹按钮
        /// </summary>
        public void TriggerGunReloadAnimation()
        {
            AIData aiData = playerEntity.AIEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            // 不允许近战状态下换弹
            if (aiData.battleState == BattleState.Boxing)
            {
                return;
            }
            
            // 子弹数量不够
            if (!battleAgent.IsRestBulletCountEnough())
            {
                return;
            }
            
            // 满子弹
            if (battleAgent.IsRestBulletCountFull())
            {
                return;
            }
            
            if (animationAgent.CanDoNextAnimation())
            {
                animationAgent.PlayHandGunReload();
            }
        }

        /// <summary>
        /// 按下投掷手雷按钮开始瞄准
        /// </summary>
        public void TriggerGrenadeAimAnimation()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
            BattleAgent battleAgent = aiEntity.battleAgent;
            
            if (!animationAgent.CanDoNextAnimation())
            {
                return;
            }
            
            // 弹匣剩余子弹数量
            if (battleAgent.GetRestBulletCount() <= 0)
            {
                if (battleAgent.IsRestBulletCountEnough())
                {
                    // 武器还有子弹
                    if (!battleAgent.IsRestBulletCountFull())
                    {
                        animationAgent.PlayGrenadeReload();
                    }
                }
                else
                {
                    // 没有子弹，切换武器
                    int weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(true);
                    if (weaponId > 0)
                    {
                        EuipAndSwitchWeapon(weaponId);
                    }
                    else
                    {
                        weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(false);
                        if (weaponId > 0)
                        {
                            EuipAndSwitchWeapon(weaponId);
                        }
                    }
                }
                return;
            }
            
            // 切换瞄准状态
            EnterAimingState(AimingState.Grenade);
            
            // 切换相机模式
            inputCamera.ControlMode = CameraControlMode.Input;
            // 显示抛物线
            GenerateParabola("Assets/ResourcesAssets/Hanging/Prefabs/Effects/sfx_parabola.prefab", 1, 0);
            _ShowParabola = true;
        }
        
        /// <summary>
        /// 松开投掷手雷按钮扔出手雷
        /// </summary>
        public void TriggerGrenadeThrowAnimation()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
            BattleAgent battleAgent = aiEntity.battleAgent;
            
            // 弹匣剩余子弹数量
            if (battleAgent.GetRestBulletCount() <= 0)
            {
                if (battleAgent.IsRestBulletCountEnough())
                {
                    // 武器还有子弹
                    if (!battleAgent.IsRestBulletCountFull() && animationAgent.CanDoNextAnimation())
                    {
                        animationAgent.PlayGrenadeReload();
                    }
                }
                else
                {
                    // 没有子弹，切换武器
                    int weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(true);
                    if (weaponId > 0)
                    {
                        EuipAndSwitchWeapon(weaponId);
                    }
                    else
                    {
                        weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(false);
                        if (weaponId > 0)
                        {
                            EuipAndSwitchWeapon(weaponId);
                        }
                    }
                }
                return;
            }
            
            // 切换瞄准状态
            EnterAimingState(AimingState.Grenade);
            
            // 切换相机模式
            inputCamera.ControlMode = CameraControlMode.Input;
            if (animationAgent.CanDoNextAnimation())
            {
                if (!_Parabola)
                {
                    // 防止快速点击松开，抛物线还未生成
                    CalculatePrabolaParams();
                }
                animationAgent.PlayThrowGrenade(_ParabolaEndPoint, _ParabolaMaxHeight);
            }
            // 隐藏抛物线
            DestroyParabola();
            _ShowParabola = false;
        }

        /// <summary>
        /// 按下RPG火箭筒瞄准
        /// </summary>
        public void TriggerRPGAimAnimation()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            
            // 弹匣剩余子弹数量
            if (battleAgent.GetRestBulletCount() <= 0 && battleAgent.GetCapacityCount() > 0)
            {
                if (battleAgent.IsRestBulletCountEnough())
                {
                    // 武器还有子弹
                    if (!battleAgent.IsRestBulletCountFull())
                    {
                        animationAgent.PlayRPGReload();
                    }
                }
                else
                {
                    // 没有子弹，切换武器
                    int weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(false);
                    if (weaponId > 0)
                    {
                        EuipAndSwitchWeapon(weaponId);
                    }
                }
                return;
            }
            
            // 切换瞄准状态
            EnterAimingState(AimingState.NormalAim);
        }
        
        /// <summary>
        /// 松开RPG火箭筒开火
        /// </summary>
        public void TriggerRPGFireAnimation()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            AnimationAgent animationAgent = playerEntity.AIEntity.viewer.animationAgent;
            BattleAgent battleAgent = playerEntity.AIEntity.battleAgent;
            
            
            // 弹匣剩余子弹数量
            if (battleAgent.GetRestBulletCount() <= 0 && battleAgent.GetCapacityCount() > 0)
            {
                if (battleAgent.IsRestBulletCountEnough())
                {
                    // 武器还有子弹
                    if (!battleAgent.IsRestBulletCountFull())
                    {
                        animationAgent.PlayRPGReload();
                    }
                }
                else
                {
                    // 没有子弹，切换武器
                    int weaponId = aiEntity.WeaponSystem.GetCanUseFirstPriorityWeaponId(false);
                    if (weaponId > 0)
                    {
                        EuipAndSwitchWeapon(weaponId);
                    }
                }
                return;
            }
            
            // 切换瞄准状态
            EnterAimingState(AimingState.NormalAim);
            
            // 切换相机模式
            inputCamera.ControlMode = CameraControlMode.Input;

            if (animationAgent.CanDoNextAnimation())
            {
                LibertyWeapon libertyWeapon = aiEntity.weapon;
                if (libertyWeapon != null)
                {
                    Transform lockPoint = LibertyAIUtils.PlayerController.playerLockTargetHelper.GetCurrentLockTargetEffect();
                    if (lockPoint)
                    {
                        Vector3 direction = (lockPoint.position - libertyWeapon.FirePoint.position).normalized;
                        animationAgent.PlayRPGFire(libertyWeapon.FirePoint.position, direction);
                    }
                    else
                    {
                        animationAgent.PlayRPGFire(libertyWeapon.FirePoint.position, libertyWeapon.FirePoint.forward);
                    }
                }
            }
        }

        void LateUpdate()
        {
            UpdateParabola();
        }

        private Parabola _Parabola = null;
        private float _ParabolaRigidbodyMass = 1f;
        private float _ParabolaRigidbodyDrag = 0f;
        private bool _ShowParabola = false;
        private Vector3 _ParabolaEndPoint = Vector3.zero;
        private float _ParabolaMaxHeight = 0f;
        
        /// <summary>
        /// 生成抛物线
        /// </summary>
        /// <param name="path"></param>
        public void GenerateParabola(string path, float mass, float drag)
        {
            if (_Parabola)
            {
                try
                {
                    LibertyPoolMgr.GetInstance().Push(_Parabola.AssetPath, _Parabola.gameObject);
                }
                catch (Exception e)
                {
                    throw;
                } 
            }
            
            _Parabola = null;
            LibertyPoolMgr.GetInstance().Pop(path, go =>
            {
                if (!_ShowParabola)
                {
                    LibertyPoolMgr.GetInstance().Push(path, go);
                    _Parabola = null;
                    return;
                }
                _Parabola = go.GetComponent<Parabola>();
                _Parabola.ClearPoints();
                _Parabola.AssetPath = path;
                _ParabolaRigidbodyMass = mass;
                _ParabolaRigidbodyDrag = drag;
                // UpdateParabola();
                go.SetActive(true);
            }, false);
        }
        
        void CalculatePrabolaParams()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            Transform playerTransform = aiEntity.viewer.animator.transform;

            // 计算相机方向和水平方向的夹角
            Transform inputCameraTransform = LibertyAIUtils.PlayerController.cameraController.inputVirtualCamera.transform;
            Vector3 cameraForward = inputCameraTransform.forward;
            Vector3 horizontalForward = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
            float signedDegree = Vector3.SignedAngle(cameraForward, horizontalForward, inputCameraTransform.right);
                
            // 根据夹角计算扔出距离
            float minVerticalAngle, maxVerticalAngle;
            float range = _GrenadeRange;
            if(aiEntity.WeaponSystem.EquippedGrenade.Config != null)
            {
                range = aiEntity.WeaponSystem.EquippedGrenade.Config.range;
            }
            LibertyAIUtils.PlayerController.inputCamera.GetCameraInputVerticalAngleLimit(out minVerticalAngle, out maxVerticalAngle);
            float percent = Mathf.Clamp01((signedDegree - minVerticalAngle) / (maxVerticalAngle - minVerticalAngle));
            float distance = Mathf.Lerp(0.5f, range, _GrenadeDistanceCurve.Evaluate(percent));
            // Debug.LogError($"SignedDegree: {signedDegree} Percent: {percent} Distance: {distance}");

            

            Vector3 endPoint = playerTransform.position + playerTransform.forward * distance;
            float maxHeight = Mathf.Lerp(_GrenadeMinHeight, _GrenadeMaxHeight, _GrenadeHeightCurve.Evaluate(percent));
            _ParabolaEndPoint = endPoint;
            _ParabolaMaxHeight = maxHeight;
        }

        public void UpdateParabola()
        {
            if (_Parabola)
            {
                CalculatePrabolaParams();
                
                AIEntity aiEntity = playerEntity.AIEntity;
                Transform playerTransform = aiEntity.viewer.animator.transform;
                
                Vector3 startPoint;
                if (aiEntity.weapon)
                {
                    startPoint = aiEntity.weapon.transform.position;
                }
                else
                {
                    startPoint = playerTransform.position + Vector3.up;
                }
                
                _Parabola.PredictParabola(_ParabolaRigidbodyMass, _ParabolaRigidbodyDrag, startPoint, _ParabolaEndPoint, _ParabolaMaxHeight);
            }
        }

        public void DestroyParabola()
        {
            if (_Parabola)
            {
                LibertyPoolMgr.GetInstance().Push(_Parabola.AssetPath, _Parabola.gameObject);
                _Parabola = null;
            }
        }

        /// <summary>
        /// 获取当前弹夹剩余子弹
        /// </summary>
        /// <param name="totalBulletCount"></param>
        /// <returns></returns>
        public int GetBulletCount(out int totalBulletCount, out int magazineCapacity)
        {
            AIEntity aiEntity = playerEntity.AIEntity;
  
            int currentBulletCount;
            Weapon weapon = aiEntity.WeaponSystem.EquippedWeapon;
            if (weapon != null)
            {
                currentBulletCount = weapon.CurrentBullet;
                totalBulletCount = weapon.MaxBullet;
                magazineCapacity = weapon.Config.magazine_capacity;
            }
            else
            {
                currentBulletCount = 0;
                totalBulletCount = 0;
                magazineCapacity = 0;
            }
            return currentBulletCount;
        }

        public int GetGrenadeCount(out int totalBulletCount, out int magazineCapacity)
        {
            AIEntity aiEntity = playerEntity.AIEntity;

            int currentBulletCount;
            Weapon weapon = aiEntity.WeaponSystem.EquippedGrenade;
            if (weapon != null)
            {
                currentBulletCount = weapon.CurrentBullet;
                totalBulletCount = weapon.MaxBullet;
                magazineCapacity = weapon.Config.magazine_capacity;
            }
            else
            {
                currentBulletCount = 0;
                totalBulletCount = 0;
                magazineCapacity = 0;
            }
            return currentBulletCount;
        }
        
        /// <summary>
        /// 获取重新装弹cd
        /// </summary>
        /// <param name="reloadCD">重新装弹总时长</param>
        /// <returns></returns>
        public float GetReloadCD(out float reloadCD)
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
            PbWeaponDataConfig weaponDataConfig = aiEntity.WeaponSystem.EquippedWeapon.Config;
            if (weaponDataConfig != null)
            {
                reloadCD = weaponDataConfig.reload_CD;
            }
            else
            {
                reloadCD = 1;
            }
            return animationAgent.reloadFinishTimestamp;
        }

        /// <summary>
        /// 获取生命值
        /// </summary>
        /// <param name="maxHP"></param>
        /// <returns></returns>
        public int GetHP(out int maxHP)
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            maxHP = aiEntity.propertyDataConfig.hp;
            return aiEntity.data.hp;
        }

        /// <summary>
        /// 玩家重生
        /// </summary>
        public void RebornPlayer()
        {
            AIEntity aiEntity = playerEntity.AIEntity;
            // 重置动画
            AnimationAgent animationAgent = aiEntity.viewer.animationAgent;
            animationAgent.SetDisableOperate(false,0,true);
            animationAgent.ResetAnimationAgent();
            aiEntity.battleAgent.UnLoadWeapon();
            // 删除抛物线
            DestroyParabola();
            // 刷新角色属性
            PbAIPropertyDataConfig propertyDataConfig = LibertyConfigManager.GetInstance().GetAIPropertyDataConfig(LibertyConfigManager.PLAYER_PROPERTY_NPCID);
            aiEntity.setPropertyDataConfig(propertyDataConfig);
            EuipAndSwitchWeapon(aiEntity.propertyDataConfig.weapon_id);
            ReleaseInvincible();
        }
        
        public void ReleaseInvincible()
        {
            playerEntity.AIEntity.data.invincible = false;
            playerEntity.AIEntity.data.animInvincible = false;
        }
        
        /// <summary>
        /// 获取玩家周围敌人
        /// </summary>
        /// <param name="range"></param>
        /// <param name="enemies"></param>
        /// <param name="positions"></param>
        /// <returns></returns>
        public int GetEnemiesAround(int range, out int[] enemies, out bool[] isBosses)
        {
            if (_enemiesAround == null)
            {
                _enemiesAround = new int[PhysicsUtils.MAX_NOALLOC_LENGTH];
                _enemiesAroundIsBoss = new bool[PhysicsUtils.MAX_NOALLOC_LENGTH];
            }
            
            AIEntity aiEntity = playerEntity.AIEntity;
            AIData aiData = aiEntity.data;
            Vector3 position = aiEntity.viewer.animator.transform.position;
            
            // // 物理检测
            // int count;
            // Collider[] results = PhysicsUtils.OverlapSphereNonAlloc(out count, position, range, BattleAgent.BoxingOnHitLayerMaskName);
            //
            // // 查找敌人
            // int enemiesCount = 0;
            // for (int i = 0; i < count; ++i)
            // {
            //     Collider collider = results[i];
            //     // 检测是否是敌人
            //     if (BattleAgent.CheckIsEnemyByTag(aiData.side, collider))
            //     {
            //         AIEntity target = LibertyAIUtils.GetNpc(int.Parse(collider.name));
            //         if (target && target.data.isAlive && target.data.npcAIModel!=NpcAIModel.Escape)
            //         {
            //             switch (target.data.npcStatus)
            //             {
            //                 case NpcStatus.Battle:
            //                 case NpcStatus.OnHit:
            //                     {
            //                         _enemiesAround[enemiesCount] = target.data.uniqueId;
            //                         enemiesCount++;
            //                     }
            //                     break;
            //             }
            //         }
            //     }
            // }
            
            // 使用非物理的检测方式
            int enemiesCount = 0;
            foreach (var target in LibertyAIUtils.AIManager.NpcBirthManager.AIEntities.Values)
            {
                if (target)
                {
                    // 检测是否是敌人
                    if (BattleAgent.CheckIsEnemyByTag(aiData.side, target.onHitCollider))
                    {
                        if (target.data.isAlive)
                        {
                            switch (target.data.npcStatus)
                            {
                                case NpcStatus.Battle:
                                case NpcStatus.OnHit:
                                    {
                                        _enemiesAround[enemiesCount] = target.data.uniqueId;
                                        _enemiesAroundIsBoss[enemiesCount] = target.data.isBoss;
                                        enemiesCount++;
                                    }
                                    break;
                            }
                        }
                    }
                }

                if (enemiesCount >= PhysicsUtils.MAX_NOALLOC_LENGTH)
                {
                    break;
                }
            }

            enemies = _enemiesAround;
            isBosses = _enemiesAroundIsBoss;

            return enemiesCount;   
        }
        
        /// <summary>
        /// 获取AIEntity的位置
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="position"></param>
        /// <returns></returns>
        public bool GetAIEntityPosition(int uniqueId, out Vector3 position)
        {
            AIEntity target = LibertyAIUtils.GetNpc(uniqueId);
            if (target)
            {
                position = target.viewer.animator.transform.position;
                return true;
            }
            else
            {
                position = Vector3.zero;
                return false;
            }
        }

        /// <summary>
        /// 设置当前锁定目标特效是否可见
        /// </summary>
        /// <param name="visible"></param>
        public void SetCanShowLockTarget(bool visible)
        {
            // bool needRefresh = playerLockTargetHelper.CanShowLockTarget != visible;
            playerLockTargetHelper.CanShowLockTarget = visible;
            // if (needRefresh)
            // {
            //     playerLockTargetHelper.RefreshCurrentLockTarget();
            // }
        }

        /// <summary>
        /// 是否可移动
        /// </summary>
        /// <returns></returns>
        public bool GetCanMove()
        {
            return inputController.CanMove;
        }

        public bool GetCanChangeWeapon()
        {
            return inputController.CanChangeWeapon;
        }

        public List<Weapon> GetWeaponList()
        {
            return playerEntity.AIEntity.WeaponSystem.GetWeapons();
        }

        public Vector3 GetPlayerTargetLerpPosition()
        {
            return playerEntity.AIEntity.data.TargetLerpPosition;
        }
    }
}
